|
1
|
|
|
import { DateTime } from 'luxon' |
|
2
|
|
|
import { BaseModel, column, belongsTo, BelongsTo, manyToMany, ManyToMany, hasMany, HasMany } from '@ioc:Adonis/Lucid/Orm' |
|
3
|
|
|
import Merchant from 'App/Models/Merchant' |
|
4
|
|
|
import Product from 'App/Models/Product' |
|
5
|
|
|
import ReorderNotification from 'App/Models/ReorderNotification' |
|
6
|
|
|
|
|
7
|
|
|
export default class Ingredient extends BaseModel { |
|
8
|
|
|
@column({ isPrimary: true }) |
|
9
|
|
|
public id: number |
|
10
|
|
|
|
|
11
|
|
|
@column() |
|
12
|
|
|
public userId: number |
|
13
|
|
|
|
|
14
|
|
|
// This is needed because the merchant extends the user model |
|
15
|
|
|
@column({ columnName: 'user_id'}) |
|
16
|
|
|
public merchantId: number |
|
17
|
|
|
|
|
18
|
|
|
@column() |
|
19
|
|
|
public name: string |
|
20
|
|
|
|
|
21
|
|
|
@column() |
|
22
|
|
|
public quantityAvailable: number |
|
23
|
|
|
|
|
24
|
|
|
@column() |
|
25
|
|
|
public quantitySupplied: number |
|
26
|
|
|
|
|
27
|
|
|
@column() |
|
28
|
|
|
public quantityStocked: number |
|
29
|
|
|
|
|
30
|
|
|
@column() |
|
31
|
|
|
public lastReorderAt: string |
|
32
|
|
|
|
|
33
|
|
|
@column.dateTime({ autoCreate: true }) |
|
34
|
|
|
public createdAt: DateTime |
|
35
|
|
|
|
|
36
|
|
|
@column.dateTime({ autoCreate: true, autoUpdate: true }) |
|
37
|
|
|
public updatedAt: DateTime |
|
38
|
|
|
|
|
39
|
|
|
@belongsTo(() => Merchant) |
|
40
|
|
|
public merchant: BelongsTo<typeof Merchant> |
|
41
|
|
|
|
|
42
|
|
|
@manyToMany(() => Product, { |
|
43
|
|
|
relatedKey: 'id', |
|
44
|
|
|
pivotForeignKey: 'ingredient_id', |
|
45
|
|
|
pivotRelatedForeignKey: 'product_id', |
|
46
|
|
|
pivotTable: 'product_ingredients', |
|
47
|
|
|
pivotColumns: ['id', 'quantity'] |
|
48
|
|
|
}) |
|
49
|
|
|
public products: ManyToMany<typeof Product> |
|
50
|
|
|
|
|
51
|
|
|
@column() |
|
52
|
|
|
public pivotQuantity: number |
|
53
|
|
|
|
|
54
|
|
|
@hasMany(() => ReorderNotification) |
|
55
|
|
|
public reorderNotifications: HasMany<typeof ReorderNotification> |
|
56
|
|
|
|
|
57
|
|
|
public static async isMerchantNotifiedForReorder(ingredient: Ingredient): Promise<boolean> |
|
58
|
|
|
{ |
|
59
|
|
|
const ingredientExists = await Ingredient.$getRelation('reorderNotifications') |
|
60
|
|
|
.relatedModel() |
|
61
|
|
|
.query() |
|
62
|
|
|
.where('ingredient_id', ingredient.id) |
|
63
|
|
|
.where('last_reorder_at', ingredient.lastReorderAt) |
|
64
|
|
|
.first() |
|
65
|
|
|
|
|
66
|
|
|
if (!ingredientExists) { |
|
67
|
|
|
return false |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
return true |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
public static isDueForReorder(ingredient: Ingredient): boolean |
|
74
|
|
|
{ |
|
75
|
|
|
const half = ingredient.quantityStocked / 2 |
|
76
|
|
|
const diff = ingredient.quantityStocked - ingredient.quantityAvailable |
|
77
|
|
|
|
|
78
|
|
|
return half <= diff |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|